#include "TcpConnection.hpp"
#include "EventLoop.hpp"
#include <iostream>
using std::cout;
using std::endl;
using std::bind;

namespace wd{


TcpConnection::TcpConnection(int clientfd, EventLoop* eventloop)
:_sock(clientfd)
,_sockio(clientfd)
,_localAddr(getlocalAddr())
,_peerAddr(getpeerAddr())
,_eventloop(eventloop)
{
}
    
string TcpConnection::receive(){
    char buff[65535];
    int ret = _sockio.readline(buff,sizeof(buff));
    return string(buff,ret);    
}

void TcpConnection::send(const string & msg){
    _sockio.sendn(msg.c_str(),msg.size());
}
    
bool TcpConnection::isClose() const{
    char buff[100] = {0};
    int ret = _sockio.recvPeek(buff,100);
    return ret == 0;
}

struct sockaddr_in TcpConnection::getlocalAddr(){
    struct sockaddr_in addr;
    memset(&addr,0,sizeof(addr));
    socklen_t len = sizeof(addr);
    int ret = getsockname(_sock.fd(),(struct sockaddr*)&addr,&len);
    if(ret < 0){
        perror("getsockname");
    }
    return addr;
}

struct sockaddr_in TcpConnection::getpeerAddr(){
    struct sockaddr_in addr;
    memset(&addr,0,sizeof(addr));
    socklen_t len = sizeof(addr);
    int ret = getpeername(_sock.fd(),(struct sockaddr*)&addr,&len);
    if(ret < 0){
        perror("getpeername");
    }
    return addr;

}
    
//让send功能在主线程中执行
void TcpConnection::sendInLoop(const string & msg){
    if(_eventloop){
        printf("in TcpConnection::sendInLoop\n");
        _eventloop->addFunctor(bind(&TcpConnection::send,this,msg));
    }
}

}

